/**
 * github授权
 * 第三方应用[client_id,client_secret]
 * 授权方式：用户名+密码
 * https://developer.github.com/v3/oauth_authorizations/
 * 测试脚本:
 *   curl -u username:passwd https://api.github.com/authorizations
 *   curl -X DELETE -u username:passwd https://api.github.com/authorizations/:id
 */
//  帐号1 wzq
// 拥有一个应用 app_test1
// Client ID 8a51eb5783bbfdb85606
// Client Secret e43fa359122e904b4f152b9aabcf857337de19c3
// 帐号2 dormi330
// 现在目的:dormi330向app_test1授权,使 app_test1能够访问dormi330的个人信息,公有仓库,私有仓库...

var request = require('request');

var config = {
	name: "dormi330",
	passwd: 'xxxx', // replace with your password
	scopes: ["repo", "user:email"],
	note: "admin script",
	note_url: "null",
	client_id: "8a51eb5783bbfdb85606",
	client_secret: "e43fa359122e904b4f152b9aabcf857337de19c3"
};
var uri_template = 'https://$name:$passwd@api.github.com/authorizations/clients/$client_id';

function genToken(config, callback) {
	var uri = uri_template.replace('$name', config.name);
	var uri = uri.replace('$passwd', config.passwd);
	var uri = uri.replace('$client_id', config.client_id);

	var options = {
		headers: {
			'User-Agent': 'Awesome-Octocat-App'
		},
		uri: uri,
		method: 'PUT',
		json: config
	};

	// console.log(options);
	request(options, function(err, response, body) {
		if (err) {
			return console.log('error', err);
		}
		// console.log(body);
		try {
			if (typeof body === 'string')
				body = JSON.parse(body);
			var token = body.token;
			callback(null, token);
		} catch (err) {
			callback(err);
		}
	});
}

// sample body content
// { id: 14266899,
//   url: 'https://api.github.com/authorizations/14266899',
//   app:
//    { name: 'app_test1',
//      url: 'http://localhost:8080',
//      client_id: '8a51eb5783bbfdb85606' },
//   token: 'b3abf8faf4a723c14d77c1dca38dbe8640da84ec',
//   note: 'admin script',
//   note_url: 'null',
//   created_at: '2015-01-14T03:28:45Z',
//   updated_at: '2015-01-14T03:28:45Z',
//   scopes: [ 'repo', 'user:email' ] }

genToken(config, function(err, token) {
	if (err) {
		return console.log(err);
	}
	console.log(token);
	// TODO
});
